<template>
    <div class="info-box">
        <div class="title">账户信息</div>
        <el-form
            class="form-box"
            ref="formInfoRef"
            v-loading="loading"
            element-loading-text="正在识别..."
            :model="formInfo"
            :rules="rules"
            :inline="false"
            scroll-to-error
            :disabled="props.disabled"
            label-position="top"
            label-width="auto">
            <el-row v-if="isIndividuality">
                <el-col :span="24">
                    <el-form-item label="账户类型" prop="account_type">
                        <el-radio-group v-model="formInfo.account_type" @change="onChangeAccountType">
                            <el-radio :label="1">对公账户</el-radio>
                            <el-radio :label="2">经营者对私账户</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <template v-if="formInfo.account_type == 1">
                <el-row :gutter="60">
                    <el-col :span="8">
                        <el-form-item label="对公账户名称" prop="account_name">
                            <el-input
                                v-model.trim="formInfo.account_name"
                                placeholder="请输入企业对公账户名称"
                                type="text"
                                maxlength="32"
                                show-word-limit
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="对公账户号" prop="account_public">
                            <el-input
                                v-model.trim="formInfo.account_public"
                                placeholder="请输入企业对公账户号"
                                type="text"
                                maxlength="32"
                                show-word-limit
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结算时间" prop="account_settle_type">
                            <el-select v-model="formInfo.account_settle_type" placeholder="请选择结算时间" clearable>
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="60">
                    <el-col :span="16">
                        <el-form-item label="对公账户开户行信息" prop="account_bank">
                            <template #label>
                                <div class="label">
                                    对公账户开户行信息
                                    <el-tooltip
                                        class="box-item"
                                        content="支持多关键词检索，多关键词间用空格隔开，例如：上海 张江 工商"
                                        placement="top-start">
                                        <img
                                            class="icon-img"
                                            src="//img.static-keyid.cn/toolspace/scrm/2023/10/1697187985733t36wepeoawxsxlv7.png" />
                                    </el-tooltip>
                                </div>
                            </template>
                            <ZwUnityKitSelect
                                v-model="formInfo.account_bank"
                                :option="accountBankOption"
                                :disabled="props.disabled"
                                width="100%"
                                selectType="accountInfo"
                                placeholder="请输入开户支行关键词检索或填写12位联行号检索"
                                @change="onChangeBank" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="费率" prop="account_pay_rate">
                            <ZwUnityKitInputNumber v-model="formInfo.account_pay_rate" type="rate" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="60">
                    <el-col :span="8">
                        <el-form-item label=" 开户许可证图片" prop="account_license">
                            <div class="upload-img-box">
                                <ZwUnityKitCertificateUpload
                                    v-model="formInfo.account_license"
                                    v-model:imageList="account_license_url"
                                    ocrType="BANK_ACCOUNT_PERMIT"
                                    uploadLabel="上传开户许可证"
                                    :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                    :multiple="false"
                                    :disabled="props.disabled"
                                    @submit="onUploadOCR"
                                    uploadTips="支持JPG、BMP、PNG格式，图片大小不能超过1M。"
                                    validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </template>
            <template v-if="formInfo.account_type == 2">
                <el-row :gutter="240">
                    <el-col :span="16">
                        <el-form-item label="银行卡卡号面" prop="account_license_private">
                            <template #label>
                                <div class="label">
                                    银行卡卡号面<span>（请使用与经营者姓名一致的银行卡，不支持招商银行卡）</span>
                                </div>
                            </template>
                            <div style="width: 50%">
                                <div class="upload-img-box">
                                    <ZwUnityKitCertificateUpload
                                        v-model="formInfo.account_license_private"
                                        v-model:imageList="account_license_private_url"
                                        ocrType="BANK_CARD"
                                        uploadLabel="上传银行卡卡号面"
                                        :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                        uploadTips="支持JPG、BMP、PNG格式，图片大小不能超过1M。"
                                        validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M"
                                        :multiple="false"
                                        :disabled="props.disabled"
                                        @submit="onUploadBankCardOCR"
                                        @start="onStartLoading"
                                        @finished="onFinishedLoading" />
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="60">
                    <el-col :span="8">
                        <el-form-item label="银行卡号" prop="account_private">
                            <el-input
                                v-model.trim="formInfo.account_private"
                                placeholder="请输入银行卡号"
                                type="text"
                                maxlength="32"
                                show-word-limit
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结算时间" prop="account_settle_type">
                            <el-select v-model="formInfo.account_settle_type" placeholder="请选择结算时间" clearable>
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="费率" prop="account_pay_rate">
                            <ZwUnityKitInputNumber v-model="formInfo.account_pay_rate" type="rate" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="60">
                    <el-col :span="16">
                        <el-form-item label="银行卡开户行信息" prop="account_bank_private">
                            <template #label>
                                <div class="label">
                                    银行卡开户行信息
                                    <el-tooltip
                                        class="box-item"
                                        content="支持多关键词检索，多关键词间用空格隔开，例如：上海 张江 工商"
                                        placement="top-start">
                                        <img
                                            class="icon-img"
                                            src="//img.static-keyid.cn/toolspace/scrm/2023/10/1697187985733t36wepeoawxsxlv7.png" />
                                    </el-tooltip>
                                </div>
                            </template>
                            <ZwUnityKitSelect
                                v-model="formInfo.account_bank_private"
                                :option="accountBankPrivateOption"
                                :disabled="props.disabled"
                                width="100%"
                                selectType="accountInfo"
                                placeholder="请输入开户支行关键词检索或填写12位联行号检索"
                                @change="onChangeBankPrivate" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </template>
        </el-form>
    </div>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue';
import { packSelectObjUtil } from '@/commons/utils';
import constants from '@/commons/constants';

const options = reactive(packSelectObjUtil(constants.SETTLEMENT_TIME));

const emit = defineEmits(['update:modelValue']);

const props = defineProps({
    modelValue: {
        type: Object,
        default: () => {}
    },
    disabled: {
        type: Boolean,
        default: false
    },
    corpMainType: {
        type: [String, Number],
        default: 1
    }
});

const formInfo = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

/** 是否是个体工商户 */
const isIndividuality = computed(() => {
    return props.corpMainType == 2;
});

const loading = ref(false);

const formInfoRef = ref(null);

const accountBankOption = ref([]);

const accountBankPrivateOption = ref([]);

const bankName = ref('');

const bankPrivateName = ref('');

const account_license_url = ref({
    code: '',
    url: ''
});

const account_license_private_url = ref({
    code: '',
    url: ''
});

const checkAccountBankPrivate = (ruls, value, callback) => {
    if (!value) {
        return callback(new Error('请选择银行卡开户行信息'));
    }
    if (bankPrivateName.value.indexOf('招商银行') > -1) {
        return callback(new Error('对私账户暂不支持绑定招商银行卡'));
    }

    callback();
};

const rules = reactive({
    account_type: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
    account_name: [{ required: true, message: '请输入对公账户名称', trigger: 'blur' }],
    account_public: [
        { required: true, message: '请输入对公账户号', trigger: 'blur' },
        { pattern: /^\d+$/, message: '请输入正确的公账户号', trigger: 'blur' }
    ],
    account_settle_type: [{ required: true, message: '请选择结算时间', trigger: 'change' }],
    account_bank: [{ required: true, message: '请选择对公账户开户行信息', trigger: 'change' }],
    account_pay_rate: [{ required: true, message: '请输入费率', trigger: 'blur' }],
    account_license: [{ required: true, message: '请上传开户许可证', trigger: 'change' }],
    account_license_private: [{ required: true, message: '请上传银行卡卡号面', trigger: 'change' }],
    account_private: [
        { required: true, message: '请输入银行卡号', trigger: 'blur' },
        { pattern: /^\d+$/, message: '请输入正确的银行卡号', trigger: 'blur' }
    ],
    account_bank_private: [{ required: true, validator: checkAccountBankPrivate, trigger: 'change' }]
});

/**
 * 表单校验
 * @param {*} typeList 需要校验的字段，默认全校验
 */
const validate = async (typeList = []) => {
    if (typeList.length) {
        let errNum = 0;
        for (let i = 0; i < typeList?.length; i++) {
            try {
                await formInfoRef.value?.validateField(typeList[i]);
            } catch (err) {
                errNum++;
            }
        }
        return !errNum;
    } else {
        return await formInfoRef.value?.validate();
    }
};

const onUploadOCR = (val = {}) => {
    // if (!formInfo.value.account_name) {
    //     formInfo.value.account_name = val.customerName;
    // }
    // if (!formInfo.value.account_public) {
    //     formInfo.value.account_public = val.bankAccount;
    // }
};

/**
 * 银行卡ocr识别
 * @param {*} val
 */
const onUploadBankCardOCR = val => {
    // console.log(val, 'val');
    formInfoRef.value?.clearValidate('account_license_private');
    let info = val || {};
    if (!formInfo.value.account_private && val.cardNumber) {
        formInfo.value.account_private = val.cardNumber;
        formInfoRef.value?.clearValidate('account_private');
    }
};

const onChangeBank = val => {
    bankName.value = val?.label || '';
};

const onChangeBankPrivate = val => {
    bankPrivateName.value = val?.label || '';
};

/**
 * 切换账户类型 处理开户行信息
 *
 */
const onChangeAccountType = val => {
    if (val == 1) {
        if (formInfo.value.account_bank && !accountBankOption.value?.length) {
            accountBankOption.value = [
                {
                    label: bankName.value,
                    value: formInfo.value.account_bank
                }
            ];
        }
    } else if (val == 2) {
        if (formInfo.value.account_bank_private && !accountBankPrivateOption.value?.length) {
            accountBankPrivateOption.value = [
                {
                    label: bankPrivateName.value,
                    value: formInfo.value.account_bank_private
                }
            ];
        }
    }
};

const onStartLoading = () => {
    loading.value = true;
};

const onFinishedLoading = () => {
    loading.value = false;
};

watch(
    () => formInfo.value.account_license,
    (val, oldVal) => {
        if (!oldVal && val) {
            formInfoRef.value?.clearValidate('account_license');
        }
    }
);

watch(
    () => formInfo.value.account_license_private,
    (val, oldVal) => {
        if (!oldVal && val) {
            formInfoRef.value?.clearValidate('account_license_private');
        }
    }
);

watch(
    () => formInfo.value?.account_license_url,
    val => {
        if (val) {
            account_license_url.value.code = formInfo.value.account_license;
            account_license_url.value.url = formInfo.value.account_license_url;
        }
    }
);

watch(
    () => formInfo.value?.account_license_private_url,
    val => {
        if (val) {
            account_license_private_url.value.code = formInfo.value.account_license_private;
            account_license_private_url.value.url = formInfo.value.account_license_private_url;
        }
    }
);

defineExpose({
    formInfoRef,
    accountBankOption,
    accountBankPrivateOption,
    bankPrivateName,
    validate
});
</script>
<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 24px;
}
.info-box {
    margin-bottom: 16px;
    background: #ffffff;
    .title {
        padding: 16px 24px;
        font-size: 16px;
        font-weight: 500;
        color: #333333;
        line-height: 24px;
        border-bottom: 1px solid #e9e9e9;
    }
    .form-box {
        margin: 24px 24px 0;
        .label {
            display: inline-block;
            position: relative;
            span {
                font-size: 14px;
                color: rgba(153, 153, 153, 0.85);
                line-height: 22px;
            }
            .icon-img {
                position: absolute;
                margin-left: 4px;
                top: 3px;
                width: 16px;
                height: 16px;
            }
        }
        .upload-img-box {
            width: 45%;
            margin-bottom: 24px;
        }
    }
}
</style>
